<!-- 订单详情 -->
<template>
  <view class="page-wrapper order-info-page page">
    <div class="page-title">订单详情 Order Detail</div>
    <div class="wrap">
      <div class="title">
        {{ order.name }}
        <br />
        {{ order.enName }}
      </div>
      <!-- 订单类型 1.会员 2.商品 3.活动/展览 -->
      <!-- 已取消的订单不显示这些 -->
      <div v-if="order.status !== 7 && order.type == 2">
        <div class="te">{{ order.skuName + '' + order.skuEnName }}</div>
        <div class="te">x{{ order.quantity }}</div>
        <div class="te">{{ order.payPrice }}</div>
        <div class="title">收件人信息</div>
        <div class="te">
          {{ order.addressUserName + '' + order.addressPhone }}
        </div>

        <div class="te">运费 Shipping</div>
        <div class="te">¥ {{ order.payPrice < 199 ? 10 : 0 }}</div>
        <div class="title">合计 Total &#62;</div>
        <div class="te">¥ {{ order.payPrice }}</div>
      </div>

      <div class="title">订单状态 Order Status</div>
      <div class="te show-detail-tab" @click="showOrderInfo">
        <div class="left">
          {{ statusCn(order.status) }}
        </div>
        <div class="right">
          <uv-icon color="#fff" :name="isShowOrderInfo ? 'minus' : 'plus'" size="16rpx"></uv-icon>
        </div>
      </div>
      <div v-if="isShowOrderInfo">
        <div class="te">订单编号 Order Number</div>
        <div class="te">{{ order.number }}</div>
        <div class="te">下单时间 Order Time</div>
        <div class="te">{{ order.createTime }}</div>
      </div>
      <!-- 取消的订单显示这些 -->
      <div v-if="order.status == 7">
        <div class="title">退款金额 Refund Amount</div>
        <div class="te">¥ {{ order.payPrice }}</div>
      </div>
      <!-- 状态已支付，待收货，已完成可以开票，且要判断开票的状态 -->
      <div class="title" @click="onLineTicket" v-if="[2, 3, 5].includes(order.status) && order.invoiceStatus == 0">
        <div class="btn">在线开票 Online Invoicing &#62;</div>
      </div>
      <div class="te">
        {{ order.invoiceStatus == 1 ? '已开票' : order.invoiceStatus == 2 ? '开票中' : '待申请' }}
      </div>
      <!-- 当状态码为3时，显示确认收获按钮 -->
      <div class="title" @click="confirmDelivery" v-if="[3].includes(order.status)">
        <div class="btn">确认收货 Confirm Delivery &#62;</div>
      </div>

      <!--  待收货的可以申请售后 -->
      <div class="title" @click="afterSales" v-if="order.type == 2 && [2].includes(order.status)">
        <div class="btn">申请退款 Refund &#62;</div>
      </div>

      <!-- 票务的退款 -->
      <div
        class="title"
        @click="toRefundTicket"
        v-if="order.type == 3 && order.status == 5 && order.activityUserStatus == 2"
      >
        <div class="btn">申请退款 Refund &#62;</div>
      </div>

      <!--  待收货的可以申请售后 -->
      <div class="title" @click="afterSales" v-if="[3].includes(order.status)">
        <div class="btn">申请售后 After Sales &#62;</div>
      </div>
      <div class="te">
        <div class="btn" @click="showMsgBox">联系客服 &#62;</div>
      </div>
      <div style="height: 140rpx">
        <!-- 占位用 -->
      </div>
      <div class="bottom-control-box" v-if="order.status === 1">
        <div class="bottom-control-container">
          <div class="wrap">
            <div class="left-box" @click="cancelOrder">
              <div class="div">取消 Cancel</div>
            </div>
            <div class="bottom-control-btn" @click="continuePayment">支付 Pay</div>
          </div>
          <bottom-safe-area></bottom-safe-area>
        </div>
        <div>
          <div style="height: 100rpx"></div>
          <bottom-safe-area></bottom-safe-area>
        </div>
      </div>
    </div>
    <div class="modal-mask" v-if="showMSg">
      <div class="wrap-mask" @click="closeModal"></div>
      <div class="modal-contianer">
        <div class="img-box">
          <img class="img" src="@/static/icon/code.svg" mode="aspectFill" alt="" />
        </div>
        <div class="phone-num">12391284923</div>
      </div>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed } from 'vue'
import { orderInfo, orderCancel, payOrder, orderReceive, orderRefund } from '@/utils/api/order'
import { defaultAddress } from '@/utils/api/address'
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app'

const order = ref<any>({})

let id: number = 0

let showMSg = ref<boolean>(false)
const getInfo = async () => {
  const res = await orderInfo({ id })
  if (res.code === 200) {
    order.value = res.data
  }
  uni.stopPullDownRefresh()
}

// 1.待付款 2.待发货 3.待收货 4.已退款 5.已完成 6.退款异常 7.已取消
const statusCn = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '未支付  Unpaid',
    2: '已支付  Paid',
    3: '待收货  Delivered',
    4: '已退款  Refunded',
    5: '已完成  Completed',
    6: '退款异常  RefundException',
    7: '已取消  Cancelled'
  }
  return statusMap[status] || '未知状态'
}

let isShowOrderInfo = ref<boolean>(false)
const showOrderInfo = () => {
  isShowOrderInfo.value = !isShowOrderInfo.value
}
const onLineTicket = () => {
  uni.navigateTo({
    url: '/pages/applyInvoice/applyInvoice?id=' + order.value.id
  })
}
const cancelOrder = () => {
  uni.showModal({
    title: '取消订单',
    content: '确定取消订单吗？',
    success: function (res) {
      if (res.confirm) {
        orderCancel({
          id: id
        }).then((res) => {
          if (res.code === 200) {
            uni.showToast({
              title: '取消成功'
            })
            getInfo()
          }
        })
      }
    }
  })
}

let addressId = ref<number>(0)
const getDefaulAddress = async () => {
  const res = await defaultAddress()
  if (res.code === 200) {
    addressId.value = res.data.id
  }
}
// 确认收货
const confirmDelivery = async () => {
  const { data, code } = await orderReceive({
    id: order.value.id
  })

  if (code === 200) {
    uni.showToast({
      title: '收货成功'
    })
  } else {
    uni.showToast({
      title: '收货失败'
    })
  }
  setTimeout(() => {
    getInfo()
  }, 500)
}

const afterSales = () => {
  uni.navigateTo({
    url: '/pages/afterSales/afterSales?id=' + order.value.id
  })
}
const continuePayment = async () => {
  if (addressId.value === 0) {
    return
  }
  const payRes = await payOrder({
    orderId: order.value.id,
    payType: 1,
    userAddressId: addressId.value
  })
  // 支付以后跳转用的页面参数
  if (payRes.code == 200) {
    let data = JSON.parse(payRes.data)
    wx.requestPayment({
      timeStamp: data.timestamp, //时间戳
      nonceStr: data.noncestr, //随机字符串
      package: data.package, //prepay_id
      signType: data.signType, //签名算法MD5
      paySign: data.paySign, //签名'
      success(res) {
        if (res.errMsg == 'requestPayment:ok') {
          console.log('支付成功', res)
          getInfo()
          getDefaulAddress()
        } else {
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          })
          setTimeout(() => {
            getInfo()
            getDefaulAddress()
          }, 500)
        }
      },
      fail(res) {
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        })
        setTimeout(() => {
          getInfo()
          getDefaulAddress()
        }, 500)
      }
    })
  }
}

const toRefundTicket = () => {
  uni.navigateTo({
    url: '/pages/refundTicket/refundTicket?id=' + id
  })
}
const applyRefund = () => {
  console.log('申请退款')
}
const showMsgBox = () => {
  showMSg.value = true
}

const closeModal = () => {
  showMSg.value = false
}

onLoad((opt) => {
  id = opt.id
})
onShow(() => {
  getDefaulAddress()
  getInfo()
})
onPullDownRefresh(() => {
  getDefaulAddress()
  getInfo()
})
</script>

<style lang="scss" scoped>
@import './orderInfo.scss';
</style>
